﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Teein.Proxy.Bot.Model;
using System.Text.RegularExpressions;
using Teein.Proxy.Bot.Helper;
using MongoDB.Driver;
using Teein.Proxy.Bot.BLL;
using System.Net;
using System.Threading;
using MongoDB.Bson;
using System.Runtime.InteropServices;
using Teein.Proxy.Bot.BLL;
using Teein.Proxy.Bot.Model;
using Teein.Proxy.Bot.Helper;

namespace Teein.Proxy.Bot
{
    public partial class MainForm : Form
    {
        private IPProxy m_IPProxy = new IPProxy();
        private Site m_Site = new Site();
        private Account m_Account = new Account();
        private WebBrowser webBrowser = new WebBrowser();
        private string client_id = "1755208418";
        private string redirect_uri = "http://www.apphosts.net/QiYa/index.aspx";
        private string response_type = "code";
        private string client_secret = "f103f9744167e285f9b4208d08841676";
        private string AccessTokenURL = "https://api.weibo.com/oauth2/access_token";
        private string AuthorizeURL = "https://api.weibo.com/oauth2/authorize";
        private int RowIndex = 0;
        public MainForm()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
            webBrowser = webBrowser1;
            webBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser_DocumentCompleted);
            
            ipList.DataSource = m_IPProxy.Find(new QueryDocument() { { "Ping", new BsonDocument(){ {"$lt", 2000} } } }).OrderBy(p => p.Ping).ToList();
            //GetSinaAccountInfo();
            accountList.DataSource = m_Account.Find();

            Thread m_thread = new Thread(new ThreadStart(GeneralProxyIPInfo));
            m_thread.SetApartmentState(ApartmentState.STA);
            m_thread.Start();

            siteList.DataSource = m_Site.Find();
            timer1.Start();
        }

        private void GeneralProxyIPInfo()
        {
            
            IList<SiteInfo> siList = m_Site.Find();
            Regex regTR = new Regex("<tr.*?</tr>", RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled);
            Regex regTD = new Regex(">.*?</td>", RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled);
            //m_IPProxy.Delete();
            foreach (SiteInfo si in siList)
            {
                string result = new HttpRequestHelper().HttpRequestGet(si.Url);

                MatchCollection mcs = regTR.Matches(result);

                foreach (Match mc in mcs)
                {
                    MatchCollection tempmc = regTD.Matches(mc.Value);
                    if (tempmc.Count > 3)
                    {
                        QueryDocument qd = new QueryDocument() { { "IP", Convert.ToInt32(tempmc[2].Value.Replace(">", "").Replace("</td", "")) }, { "CreateDate", Convert.ToDateTime(DateTime.Now.ToString("yyyy/MM/dd")) } };
                        ProxyInfo pi = m_IPProxy.FindOne(qd);
                        if (pi == null)
                        {
                            pi = new ProxyInfo();
                        }
                        pi.IP = tempmc[1].Value.Replace(">", "").Replace("</td", "");
                        pi.Port = Convert.ToInt32(tempmc[2].Value.Replace(">", "").Replace("</td", ""));
                        pi.State = tempmc[3].Value.Replace(">", "").Replace("</td", "");
                        pi.CreateDate = Convert.ToDateTime(DateTime.Now.ToString("yyyy/MM/dd"));
                        pi.LastTime = Convert.ToDateTime(DateTime.Now.ToString("yyyy/MM/dd"));
                        pi.Ping = -1;
                        pi.IsUse = true;
                        

                        BackgroundWorker bg = new BackgroundWorker();
                        bg.DoWork += new DoWorkEventHandler(bg_DoWork);
                        bg.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bg_RunWorkerCompleted);
                        bg.RunWorkerAsync(pi);
                    }
                }
            }

            ipList.DataSource = m_IPProxy.Find().OrderBy(p => p.Ping).ToList();
        }

        void bg_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            //
        }

        void bg_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker bw = sender as BackgroundWorker;
            ProxyInfo tempitem = e.Argument as ProxyInfo;
            PingValue(tempitem);
        }

        private void PingValue(ProxyInfo tempitem)
        {
            try
            {
                WebProxy myProxy = new WebProxy(tempitem.IP, tempitem.Port);
                myProxy.BypassProxyOnLocal = true;
                DateTime dtBegin = DateTime.Now;
                string result = new HttpRequestHelper(myProxy).HttpRequestGet("http://www.baidu.com", 10000);
                double ts = DateTime.Now.Subtract(dtBegin).TotalMilliseconds;
                tempitem.Ping = ts;
                tempitem.RequestCount++;
                tempitem.LastTime = DateTime.Now;

                if (tempitem.RequestCount == 1)
                {
                    m_IPProxy.Insert(tempitem);
                }
                else
                {
                    m_IPProxy.Update(tempitem);
                }

            }
            catch (Exception e)
            {
                new ExceptionHelper().LogException(e);
            }
           
        }


        private void Init()
        {
            SiteInfo si = new SiteInfo();
            si.Url = "http://www.51proxied.com/http_fast.html";
            si.Name = "无忧最新代理";

            SiteInfo tempsi = m_Site.FindOne(new QueryDocument("Url", si.Url));
            if (tempsi == null)
            {
                m_Site.Insert(si);
            }

            si = new SiteInfo();
            si.Url = "http://www.51proxied.com/http_anonymous.html";
            si.Name = "无忧匿名代理";
            tempsi = m_Site.FindOne(new QueryDocument("Url", si.Url));
            if (tempsi == null)
            {
                m_Site.Insert(si);
            }

            si = new SiteInfo();
            si.Url = "http://www.51proxied.com/http_non_anonymous.html";
            si.Name = "无忧透明代理";
            tempsi = m_Site.FindOne(new QueryDocument("Url", si.Url));
            if (tempsi == null)
            {
                m_Site.Insert(si);
            }
        }

        public void webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) 
        { 
            if (webBrowser.ReadyState == WebBrowserReadyState.Complete)
            {
                if (webBrowser.Url.ToString().Contains("www.apphosts.net/QiYa/index.aspx") && webBrowser.Url.ToString().Contains("code="))
                {
                    //获取verify
                    string verify = FunctionHelper.GetQueryString(webBrowser.Url.Query, "code");

                    string requestString = string.Format("client_id={0}&client_secret={1}&code={2}&redirect_uri={3}&grant_type=authorization_code", client_id, client_secret, verify, redirect_uri);
                    string result = new HttpRequestHelper().HttpRequestPost(AccessTokenURL, requestString);
                    this.Text = result;
                    if (result.Contains("21325"))
                    {
                        
                        webBrowser.Url = new Uri(AuthorizeURL + "?client_id=" + client_id + "&redirect_uri=" + redirect_uri + "&response_type=" + response_type + "&t=" + DateTime.Now.Ticks);
                        System.Threading.Thread.Sleep(2000);
                        
                        return;
                    }
                    if (!string.IsNullOrEmpty(result))
                    {
                        string tokenKey = TextHelper.GetValueByName(result, "access_token");
                        string Uid = TextHelper.GetValueByName(result, "uid");
                        string expires_in = TextHelper.GetValueByName(result, "expires_in");
                        AccountInfo ai = new Account().FindOne(new QueryDocument() { { "AccountName", accountList.Rows[RowIndex].Cells["AccountName"].Value.ToString() } });
                        if (ai == null)
                        {
                            ai = new AccountInfo();
                            ai.AccountName = accountList.Rows[RowIndex].Cells["AccountName"].Value.ToString();
                            ai.AccessToken = tokenKey;
                            if (!string.IsNullOrEmpty(tokenKey))
                            {
                                ai.AuthorizeTime = DateTime.Now;
                            }
                            ai.ID = Uid;
                            ai.Password = accountList.Rows[RowIndex].Cells["Password"].Value.ToString();
                            ai.LastTime = DateTime.Now;
                            ai.CreateDate = DateTime.Now;
                            if (!string.IsNullOrEmpty(expires_in))
                            {
                                ai.Expires = Convert.ToInt32(expires_in);
                            }
                            m_Account.Insert(ai);
                        }
                        else
                        {
                            ai.AccessToken = tokenKey;
                            if (!string.IsNullOrEmpty(tokenKey))
                            {
                                ai.AuthorizeTime = DateTime.Now;
                            }
                            ai.LastTime = DateTime.Now;
                            if (!string.IsNullOrEmpty(expires_in))
                            {
                                ai.Expires = Convert.ToInt32(expires_in);
                            }
                            m_Account.Update(ai);
                        }
                    
                        accountList.Rows[RowIndex].Cells[2].Value = Uid;

                        if (!string.IsNullOrEmpty(tokenKey))
                        {
                            RowIndex++;
                            webBrowser.Document.Cookie.Remove(0, webBrowser.Document.Cookie.Count());
                            webBrowser.Navigate("http://weibo.com/logout.php?backurl=/");
                        }
                        
                    }
                }
                else if (webBrowser.Url.ToString().Contains("http://weibo.com"))
                {
                    if (RowIndex < accountList.Rows.Count)
                    {
                        IEProxy ieProxy = new IEProxy();
                        //ieProxy.CleanCookies();
                        ieProxy.RefreshIESettings(GetWebProxy().Address.ToString());
                        System.Object nullObject = 0;
                        string strTemp = String.Empty;
                        System.Object nullObjStr = strTemp;
                        webBrowser.Navigate(AuthorizeURL + "?client_id=" + client_id + "&redirect_uri=" + redirect_uri + "&response_type=" + response_type + "&t=" + DateTime.Now.Ticks, null, null, null);
                        System.Threading.Thread.Sleep(2000);
                    }
                }
                else if (webBrowser.Url.ToString().Contains("www.apphosts.net/QiYa/index.aspx"))
                {
                    if (RowIndex < accountList.Rows.Count)
                    {
                        AutoLogin(accountList.Rows[RowIndex].Cells["AccountName"].Value.ToString(), accountList.Rows[RowIndex].Cells["Password"].Value.ToString());
                       
                    }
                }

            }
        }


        private void AutoLogin(string strUserID, string strPWD)
        {
            webBrowser.Document.GetElementById("userId").SetAttribute("value", strUserID.Trim());
            webBrowser.Document.GetElementById("passwd").SetAttribute("value", strPWD.Trim());


            //string code = ucch.GetSingleBmpCode(pics[i], 128);   //得到代码串

            if (HasCheckCode())
            {
                ProxyInfo pi = m_IPProxy.Find(new QueryDocument() { { "Ping", new BsonDocument() { { "$lt", 2000 } } }, { "IsUse", true } }).OrderBy(p => p.Ping).FirstOrDefault();
                pi.IsUse = false;
                m_IPProxy.Update(pi);

                if (RowIndex < accountList.Rows.Count)
                {
                    IEProxy ieProxy = new IEProxy();
                    ieProxy.RefreshIESettings(GetWebProxy().Address.ToString());
                    System.Object nullObject = 0;
                    string strTemp = String.Empty;
                    System.Object nullObjStr = strTemp;
                    webBrowser.Navigate(AuthorizeURL + "?client_id=" + client_id + "&redirect_uri=" + redirect_uri + "&response_type=" + response_type + "&t=" + DateTime.Now.Ticks, null, null, null);
                    System.Threading.Thread.Sleep(2000);
                }
            }
            else
            {
                HtmlElementCollection elements = webBrowser.Document.GetElementsByTagName("a");
                foreach (HtmlElement item in elements)
                {
                    if (item.GetAttribute("className") == "WB_btn_oauth formbtn_01")
                    {
                        item.InvokeMember("click");
                        break;
                    }
                }
            }
        }

        private bool HasCheckCode()
        {
            HtmlElementCollection links = webBrowser.Document.Links;
            bool result = false;

            //foreach (HtmlElement item in links)
            //{
            //    if (item.InnerText == "换一换")
            //    {
            //        if (item.Parent.Style != "DISPLAY: none")
            //        {
            //            result = true;
            //        }
            //        break;
            //    }
            //}
            HtmlElementCollection imgs = webBrowser.Document.Images;
            foreach (HtmlElement item in imgs)
            {
                if (!string.IsNullOrEmpty(item.GetAttribute("Src")) && item.GetAttribute("node-type") == "pincode")
                {
                    result = true;
                    //WebClient wc = new WebClient();
                    //string fileName = System.IO.Directory.GetCurrentDirectory() + "\\TempFile\\" +DateTime.Now.ToString("yyyyMMddHHmmss") + ".jpg";

                    //if (!System.IO.Directory.Exists(System.IO.Directory.GetCurrentDirectory() + "\\TempFile\\"))
                    //{
                    //    System.IO.Directory.CreateDirectory(System.IO.Directory.GetCurrentDirectory() + "\\TempFile\\");
                    //}

                    //wc.DownloadFile(item.GetAttribute("Src"), fileName);
                    //UnCheckCodeHelper ucch = new UnCheckCodeHelper(new Bitmap(fileName));
                    //ucch.GrayByPixels(); //灰度处理
                    //ucch.GetPicValidByValue(128, 4); //得到有效空间
                    //Bitmap[] pics = ucch.GetSplitPics(4, 1);     //分割
                    //StringBuilder sb = new StringBuilder();
                    //foreach (Bitmap pic in pics)
                    //{
                    //    sb.Append(ucch.GetSingleBmpCode(pic, 128));
                    //}
                    
                    break;
                }
            }

            return result;
        }

        private WebProxy GetWebProxy()
        {
            WebProxy myProxy = null;
            ProxyInfo pi = m_IPProxy.Find(new QueryDocument() { { "Ping", new BsonDocument() { { "$lt", 2000 } } }, { "IsUse",true } }).OrderBy(p => p.Ping).FirstOrDefault();
            if (pi != null)
            {
                myProxy = new WebProxy(pi.IP, pi.Port);
                myProxy.BypassProxyOnLocal = true;
            }

            return myProxy;
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            IEProxy ieProxy = new IEProxy();
            ieProxy.RefreshIESettings(GetWebProxy().Address.ToString());
            System.Object nullObject = 0;
            string strTemp = String.Empty;
            System.Object nullObjStr = strTemp;
            webBrowser.Navigate(AuthorizeURL + "?client_id=" + client_id + "&redirect_uri=" + redirect_uri + "&response_type=" + response_type + "&t=" + DateTime.Now.Ticks, null, null, null);
        }

        #region 获取帐号
        private IList<AccountInfo> GetSinaAccountInfo()
        {
            IList<AccountInfo> aiList = new List<AccountInfo>();
            new Account().Delete();
            DataSet ds = Teein.Proxy.SqlHelper.SqlHelper.ExecuteQuery(Teein.Proxy.SqlHelper.SqlHelper.ConnectionStringCore,CommandType.Text,
            @"select accountID,name,loginName,loginPwd
            from PersonalAccounts
            where [type] = 0
            and isvalid = 1
            and isopened = 1
            and loginName is not null",null);

            if (ds != null && ds.Tables.Count > 0)
            {
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    AccountInfo ai = new Model.AccountInfo();
                    ai.AccountName = Convert.ToString(dr["loginName"]);
                    ai.Password = Convert.ToString(dr["loginPwd"]);
                    ai.ID = Convert.ToString(dr["accountID"]);
                    ai.CreateDate = DateTime.Now;
                    new Account().Insert(ai);
                    aiList.Add(ai);
                }
            }

            return aiList;
        }
        #endregion

        private void timer1_Tick(object sender, EventArgs e)
        {
            AutoLogin(accountList.Rows[RowIndex].Cells["AccountName"].Value.ToString(), accountList.Rows[RowIndex].Cells["Password"].Value.ToString());
        }
    }
}


         
